package com.xiaomage.slide

import android.content.Context
import android.graphics.Matrix
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.view.MotionEvent
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.ImageView

/**
 * Created by Administrator on 2018/3/20 0020.
 */
class SlideUtilClass2 : FrameLayout {
    constructor(context: Context):super(context)
    constructor(context: Context, attributeSet: AttributeSet):super(context,attributeSet)
    constructor(context: Context, attributeSet: AttributeSet, defStyleAttr:Int):super(context,attributeSet,defStyleAttr)
    enum class Direction{
        LEFT,RIGHT,NON
    }
    //左右自带距离，默认为13dp
    private val autoPadding=dip2px(13f)
    //正常图片宽度
    private val imageWidth=dip2px(150f)
    //正常图片高度
    private val imageHeight=dip2px(113f)
    //最大图片宽度
    private val imageWidthMax=dip2px(200f)
    //最大图片高度
    private val imageHeightMax=dip2px(150f)
    //中间图片距离左边的位置
    private val centerLeftMargin=(getWindowsWidth()-imageWidthMax)/2
    //中间图片向左可移动的最大距离
    private val centerImageMoveLeftMax=centerLeftMargin-autoPadding
    //左右两边距离顶部的距离
    private val leftAndRightTopMargin=(imageWidthMax-imageWidth)/2
    //左右两个图片的中间距离
    private val leftAndRightMaigin=getWindowsWidth()-2*autoPadding-2*imageWidth
    //最右边图片距离左边边框的距离
    private val rightImageMarginLeftParent=getWindowsWidth()-autoPadding-imageWidth
    //最右边图片移动到中间的距离
    private val rightImageToCenter=getWindowsWidth()-imageWidth-autoPadding-centerLeftMargin
    //一张图片旋转一周移动的X位置:以3个中间图片移动到左边为基准
    private val oneCircleX=centerImageMoveLeftMax*3
    //滑动的总距离
    private var dx=0f
    //准备滑动之前的距离
    private var dxMoveBefore=0f
    //滑动方向
    private var direction=Direction.NON
    //当前位于顶部的imageview
    private var topID=1
    //所有的图片对象
    private var lists:List<MyViewLikeImage>?=null
    //求X滑动速率
    //默认滑动1dp，图片移动2dp
    private val xRate=2.0f
    //即：滑动的x坐标/图片移动的距离
   //private val xRate:Float=getWindowsWidth().toFloat()/oneCircleX.toFloat()
    //为了保证三个阶段移动同步，还需要算出每个阶段的同步频率，以中间图片（list[1]）移动到最左边作为标准
    private val oneMomentRate=1f
    private val twoMomentRate=((imageWidth.toFloat()+leftAndRightMaigin.toFloat())/centerImageMoveLeftMax.toFloat())*oneMomentRate
    private val threeMomentRate=((rightImageMarginLeftParent.toFloat()-autoPadding.toFloat()-centerImageMoveLeftMax.toFloat())
            /centerImageMoveLeftMax.toFloat())*oneMomentRate

    //单次滑动距离
    private var oneDx=0f
    fun addView(lists:List<MyViewLikeImage>){
        this.lists=lists
        for(list in lists){
            addView(list)
            //list.scaleType=ImageView.ScaleType.FIT_XY
            val params=list.layoutParams as LayoutParams
            params.width=imageWidth
            params.height=imageHeight
            params.topMargin=leftAndRightTopMargin
            list.layoutParams=params
        }
        val params0=lists[0].layoutParams as LayoutParams
        params0.width=imageWidth
        params0.height=imageHeight
        params0.leftMargin=autoPadding
        params0.topMargin=leftAndRightTopMargin
        lists[0].layoutParams=params0

        val params=lists[1].layoutParams as LayoutParams
        params.width=imageWidthMax
        params.height=imageHeightMax
        params.leftMargin=centerLeftMargin
        params.topMargin=dip2px(0f)
        lists[1].layoutParams=params
        //显示到最顶部
        lists[1].bringToFront()

        val params3=lists[2].layoutParams as LayoutParams
        params3.width=imageWidth
        params3.height=imageHeight
        params3.leftMargin=rightImageMarginLeftParent
        params3.topMargin=leftAndRightTopMargin
        lists[2].layoutParams=params3

    }
    override fun onTouchEvent(event: MotionEvent): Boolean {
        ForLog.showError("onTouchEvent-" + event.action)
        when(event.action){
            MotionEvent.ACTION_DOWN ->{
                //按下操作
                oneDx=event.x
                ForLog.showError("按下操作" + oneDx)
            }
            MotionEvent.ACTION_MOVE ->{
                dxMoveBefore=dx
                dx+=(event.x-oneDx)
                ForLog.showError("dx-dx" + dx)
                //移动操作
                if(oneDx>event.x){
                    //向左滑动
                    direction=Direction.LEFT
                    leftMove()
                }else if(oneDx<event.x){
                    //向右滑动
                    direction=Direction.RIGHT
                }else{
                    direction=Direction.NON
                }
                oneDx=event.x
                ForLog.showError("ACTION_MOVE-oneDx" + oneDx)
            }
            MotionEvent.ACTION_UP ->{
                //手指离开
            }
        }
        return true
        //return super.onTouchEvent(event)
    }
    fun leftMove(){
        if(lists==null || lists!!.isEmpty() ) return
        //三个图片实际移动位置，同时只保留第一个循环的情况
        val imageDx0=(dx*xRate-centerImageMoveLeftMax)%oneCircleX
        val imageDx1=dx*xRate%oneCircleX
        ForLog.showError("imageDx1--(" + imageDx1)
        val imageDx2=(dx*xRate-2*centerImageMoveLeftMax)%oneCircleX
        splitMoment(0,imageDx0)
        splitMoment(1,imageDx1)
        splitMoment(2,imageDx2)
    }
    fun becomeTop(){
        val height0=lists!![0].measuredHeight
        val height1=lists!![1].measuredHeight
        val height2=lists!![2].measuredHeight
        val map = arrayListOf(height0,height,height2)
        map.sort()
        when(map[1]){
            height0->{
                lists!![0].bringToFront()
            }
            height1->{
                lists!![1].bringToFront()
            }
            height2->{
                lists!![2].bringToFront()
            }
        }
        when(map[2]){
            height0->{
                lists!![0].bringToFront()
            }
            height1->{
                lists!![1].bringToFront()
            }
            height2->{
                lists!![2].bringToFront()
            }
        }
    }
    private fun becomeTop(idBegin:Int){
        /*//0-- -1-->2
        //1--- 0
        //2--- 1
        var ids=idBegin-1
        if(ids<0) ids=lists!!.size-1
        if(ids>=lists!!.size) ids =0
        lists!![ids].bringToFront()*/
        //0--1
        //1--2
        //2--3
        var id2=idBegin+1
        if(id2<0) id2=lists!!.size-1
        if(id2>=lists!!.size) id2=0
        lists!![id2].bringToFront()
    }


    /**
     * 分割三个阶段：
     * di--->图片list下标
     * inDx:移动的位置
     */
    private fun splitMoment(id:Int,inDx: Float){
        //进行分割
        if(inDx<0 && inDx>=-centerImageMoveLeftMax){
            //第一阶段
            if(-inDx>=centerImageMoveLeftMax/2){
                becomeTop(id)
            }
            leftMove(id,1,-inDx)
        }else if(inDx<-centerImageMoveLeftMax &&
                inDx>=-2*centerImageMoveLeftMax){
            //第二阶段
            val momentDx=-(inDx+centerImageMoveLeftMax)
            leftMove(id,2,momentDx*twoMomentRate)
        }else{
            //第三阶段
            val momentDx=-(inDx+2*centerImageMoveLeftMax)
            ForLog.showError("第三阶段imageDx1--(" + momentDx)
            leftMove(id,3,momentDx*threeMomentRate)
        }
    }
    /**
     *  di--->图片list下标
     *  moment--->第几阶段，取值有：1,2,3
     *  momentDx--->该阶段移动的距离，记住，只是这个阶段的移动距离，并且已经根据速率换算完成了，并且momentDX>0
     */
    fun leftMove(id:Int,moment:Int,momentDx:Float){
        when(moment){
            1->{
                //阶段1，
                val params=lists!![id].layoutParams as LayoutParams
                val width=(imageWidthMax.toFloat()
                        -((imageWidthMax.toFloat()-imageWidth.toFloat())/centerImageMoveLeftMax.toFloat())
                        *momentDx).toInt()
                val height=(imageHeightMax.toFloat()
                        -((imageHeightMax.toFloat()-imageHeight.toFloat())/centerImageMoveLeftMax.toFloat()) *momentDx).toInt()
                val marginTop=(((leftAndRightTopMargin.toFloat())/centerImageMoveLeftMax.toFloat()) *momentDx).toInt()
                params.width= width
                params.height=height
                params.leftMargin=(autoPadding+centerImageMoveLeftMax-momentDx).toInt()
                params.topMargin=marginTop
                lists!![id].layoutParams=params
            }
            2->{
                //阶段2
                val params=lists!![id].layoutParams as LayoutParams
                params.width=imageWidth
                params.height=imageHeight
                params.leftMargin=(autoPadding+momentDx).toInt()
                params.topMargin=leftAndRightTopMargin
                lists!![id].layoutParams=params
            }
            3->{
                val params=lists!![id].layoutParams as LayoutParams
                val width=(imageWidth.toFloat()
                        +(imageWidthMax.toFloat()-imageWidth.toFloat())/
                        rightImageToCenter*momentDx).toInt()
                val height=(imageHeight.toFloat()
                        +(imageHeightMax.toFloat()-imageHeight.toFloat())/
                        rightImageToCenter*momentDx).toInt()
                val marginTop=(leftAndRightTopMargin.toFloat()-
                        (leftAndRightTopMargin.toFloat())/rightImageToCenter*momentDx).toInt()
                params.width=width
                params.height=height
                params.leftMargin=(rightImageToCenter-momentDx+centerLeftMargin).toInt()
                params.topMargin=marginTop
                lists!![id].layoutParams=params
               // becomeTop(id)
            }
        }

    }

    fun dip2px(dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    /**
     * 获取屏幕宽度
     * @return
     */
    fun getWindowsWidth(): Int {
        //之前方法
        /* WindowManager windowManager= (WindowManager) MyApplication.getInstance().getSystemService(Context.WINDOW_SERVICE);
        return  windowManager.getDefaultDisplay().getWidth();*/
        val displayMetrics = DisplayMetrics()
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        //返回px
        return displayMetrics.widthPixels
    }

    //水平倾斜
    private fun testSkewX(mTestMatrixImageView: ImageView) {
        val matrix = Matrix()
        matrix.setSkew(0.5f, 0f)
        mTestMatrixImageView.setImageMatrix(matrix)
    }

    // 垂直倾斜
    private fun testSkewY(mTestMatrixImageView: ImageView) {
        val matrix = Matrix()
        matrix.setSkew(0f, 0.5f)
        mTestMatrixImageView.setImageMatrix(matrix)
    }

    // 水平且垂直倾斜
    private fun testSkewXY(mTestMatrixImageView: ImageView) {
        val matrix = Matrix()
        matrix.setSkew(0.5f, 0.5f)
        mTestMatrixImageView.setImageMatrix(matrix)
    }
}